import base64
import json
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import time
import requests
import schedule
from Crypto.Cipher import AES
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Util.Padding import unpad

import ey

#前端参数加密
public_key ="""-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCEqv2TMxj/EgXmCO9zbyiIA/omXprrrmZhudN237lQ3qWSsxaPZlU0c79PtEEEc8nW/wAPkzUIiuOWX4N9SebZYBh+7+VmeFuyjNvMKOFTxdoQdVlWk4u8k3Jm4OBigH4YgtcSrU+LmZLQ7DD5zp9IBxWpUVewVrYyehfUHx3ppwIDAQAB
-----END PUBLIC KEY-----"""

private_key = """-----BEGIN PRIVATE KEY-----
MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIDbjG/ikFCjFb2I7z36vCgIr8I+KpxcM9WPS9BgHEQwvTBhGXgIP9nafFfxJmR+qway6vzUOnHp51yVim4/pTeHT3alxta5ZPJFHzKEYiFYDT6CYIkQopVB9unSFFT0ab8Yf5RWCZz7RxhYgbHRJKxUEDQkKMaLwv9fKLqEhhJxAgMBAAECgYACvCYz7bwgagW5GyHwz9SUiPKqDcW7wd07yCnUx2VyMRKi5zyyJoKsbg27lBu7gFDC+KMyMJL4/fzyIx5oDqPEDT4N8qDtmwVZnyeNrqwS0VbfuxpGkVsnDJaRBs3w7CM9uiJAtKuczzT7bNxUBXHHJCqbBelVMjPtGZHL6yKAHQJBALknPRkbjs/uO63jmbir3Hl4Vj2Mhtu9xOSe3blsbrgTYluOlOVC4x750RFbGv95NNfqhRbZN706iPrMF2SD2VcCQQCyKdieXBm6LG0/9yn2RS2aukEqJCB0/cTRXCrDRGJDqzrOPrE80X8AOmPVRnMoNKcpYCx46KjXh01xob8cnm13AkAyKetnzguXUlhg+HVBj26ginXzHwu6pWOe/VvdTP+CZ94SKEM3CjQ2xEBcj251IQWsKiH82sU7Q4yxRnJgDUjpAkAjY8CNpEnP+2cwH46MRq2KYJj1H/v6gTYJSD+OThUez/J8aWOXax3JE9Ak2zugruTNiTcMRVrUhSHTAogNzUJ9AkAH1eChg3LIztFf8Zky6/V9p5d0HbJ4sfyt9BBBXSN3qGWPdJX/JXv1R/GzSUIXxcMsmdlOHm6pvR1L/giSVWAH
-----END PRIVATE KEY-----"""

## res  后端返回解密
res_iv = b'wt#f7iZbHC*j5Z7F'
res_private_key="8yoHY1JYh7/D2yTxG27ocw==".encode("utf-8")


qq_mail_password = 'wpjcleztuiwybbhj'

res_private_key="8yoHY1JYh7/D2yTxG27ocw==".encode("utf-8")

doctor_code = {
    '杨迎': '3002',
    '徐凯虹': '1133',
    '王智婉':'1127'
}

keep_running= True

query_count = 1


def send_email(sender_email, sender_password, recipient_email,subject,body):
    # 创建一个 MIMEMultipart 对象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = recipient_email
    msg['Subject'] = subject

    # 邮件内容
    msg.attach(MIMEText(body, 'plain'))
    # 设置SMTP服务器并发送邮件
    try:
        # 请使用合适的 SMTP 服务器和端口
        server = smtplib.SMTP_SSL('smtp.qq.com', 465)
        server.login(sender_email, sender_password)
        server.send_message(msg)
        print("邮件发送成功！")
    except Exception as e:
        print(f"邮件发送失败：{e}")
    finally:
        server.quit()  # 关闭与SMTP服务器的连接
#加密参数解密
def decryption_query(decryption_data):
    # base64解码
    base64_decode_decryption_data = base64.b64decode(decryption_data)
    # 获取私钥
    import_private_key= RSA.importKey(private_key.encode("utf-8"))
    pk = PKCS1_v1_5.new(import_private_key)
    # 进行解密
    text = []
    for i in range(0, len(base64_decode_decryption_data), 128):
        cont = base64_decode_decryption_data[i:i + 128]
        text.append(pk.decrypt(cont, 1))
    text = b''.join(text)
    decode_decryption_data = text.decode()
    print(decode_decryption_data)
    return decode_decryption_data

#解密查询结果
def decryption_result(encrypt_data):
    # 将Base64编码的密文解码为字节
    ciphertext = base64.b64decode(encrypt_data)

    # 创建AES解密器
    cipher = AES.new(res_private_key, AES.MODE_CBC, res_iv)

    # 解密并去除填充
    decrypted = unpad(cipher.decrypt(ciphertext), AES.block_size)

    decrypted_str = decrypted.decode("utf-8")
    print(f"请求结果解密:{decrypted_str}")
    return decrypted_str

#查询加密
def encrypt_query(query_data):
    data = json.dumps(query_data)
    # 获取公钥
    publickey = RSA.importKey(public_key)
    # 分段加密
    pk = PKCS1_v1_5.new(publickey)
    encrypt_data = []
    for i in range(0, len(data), 100):
        cont = data[i:i + 100]
        encrypt_data.append(pk.encrypt(cont.encode()))
    # 加密完进行拼接
    encrypt_data_bytes = b''.join(encrypt_data)
    # base64进行编码
    real_encrypt_data = base64.b64encode(encrypt_data_bytes).decode()
    return real_encrypt_data

def get_campus():
    url = 'https://pay.czey.com:8443/apiV2/appointReg/getCampus'
    query_data = {
        "orgCodg": "H32040200065",
        "testFlag": "1"
    }
    data = encrypt_query(query_data)
    requests.packages.urllib3.disable_warnings()
    response = requests.post(url, json={"encryptData":data}, verify=False,headers={'encrypt': '4'})
    query_data_encrypt = response.json()
    if query_data_encrypt['data']:
        query_data_decrypt = decryption_result(query_data_encrypt['data'])
        print(query_data_decrypt)


def get_source_info():
    url = 'https://pay.czey.com:8443/apiV2/appointReg/getSourceInfo'
    query_data = {
        "drCode": doctor_code['王智婉'],
        "deptCode":'3002' ,
        "hisAreaCody": "06",
        "scheduleBegDate": "2024-12-02",
        "scheduleEndDate": "2024-12-06",
        "tradeSource": "05"
    }
    data = encrypt_query(query_data)
    requests.packages.urllib3.disable_warnings()
    response = requests.post(url, json={"encryptData": data}, verify=False, headers={'encrypt': '4'})
    print(response.text)
    query_data_encrypt = response.json()
    print(f"请求返回结果:{query_data_encrypt}")
    if query_data_encrypt['data']:
        query_data_decrypt = decryption_result(query_data_encrypt['data'])
        result_data = json.loads(query_data_decrypt)
        for schedule in result_data[0]['drScheduList']:
            for time_schedult in schedule['timeintervallist']:
                schedule_date = schedule['scheduleDate']
                schedule_beg_time = time_schedult['begntime']
                schedule_end_time = time_schedult['endtime']
                left_num = int(time_schedult['leftNum'])
                if left_num > 0:
                    print(f"日期:{schedule_date} 开始时间:{schedule_beg_time} 结束时间:{schedule_end_time} 剩余预约次数:{left_num}")
                    subject = f"有空号，可以预约啦！{result_data[0]['doctorName']}"
                    body = f"有空号，可以预约啦！{result_data[0]['doctorName']}医生{schedule_date} {schedule_beg_time}-{schedule_end_time}"
                    send_email('czbabl@vip.qq.com', qq_mail_password, '673741115@qq.com',subject,body);
                    ey.keep_running = False
                    break;
        ey.query_count += 1
        if ey.query_count % 20 == 0:
            subject = f"正查询预约名额"
            body = f"正查询预约名额！{result_data[0]['doctorName']}医生"
            send_email('czbabl@vip.qq.com', qq_mail_password, '673741115@qq.com', subject, body);





if __name__ == "__main__":
    schedule.every(1).minutes.do(get_source_info)
    while ey.keep_running:
        schedule.run_pending()
        time.sleep(1)